<?php
/**
 * Created by PhpStorm.
 * User: zhanghua
 * Date: 2018/9/26
 * Time: 20:02
 */

namespace app\dlc\controller;


use app\common\controller\SunBaseController;
use app\dlc\model\AdminPerm;
use app\dlc\model\AdminRolePermRelation;
use app\dlc\service\AdminPermService;


class MenuController extends SunBaseController
{
    /**
     * 菜单管理列表展示
     * @return \think\Response
     */
    public function menuList()
    {
        //获取所有的菜单
        $menus = AdminPermService::getAllMenu();

        //一级菜单
        $menuLevel1 = [];

        //二级菜单
        $menuLevel2 = [];

        foreach ($menus as $menu){
            if($menu['menu_pid'] == 0){
                $menuLevel1[] = $menu;
            }else{
                $menuLevel2[] = $menu;
            }
        }

        $this->assign('menuLevel1',$menuLevel1);
        $this->assign('menuLevel2',$menuLevel2);

        return $this->returnHtml();
    }

    /**
     * 添加菜单
     * @return \think\Response
     */
    public function menuAdd()
    {
        if($this->request->isPost()){

            $postData = $this->request->post();

            $postData['is_menu'] = 1;

            $id = AdminPermService::save($postData);

            if($id){
                return $this->returnJson(1, '添加成功');
            }else{
                return $this->returnJson(0, '添加失败');
            }
        }

        $topMenuList = AdminPermService::getTopMenu();

        $this->assign('topMenuList', $topMenuList);

        return $this->returnHtml();
    }

    /**
     * 菜单编辑
     * @return \think\Response
     */
    public function menuEdit()
    {
        if($this->request->isPost()){

            $postData = $this->request->post();

            $id = AdminPermService::save($postData);

            if($id){
                return $this->returnJson(1, '添加成功');
            }else{
                return $this->returnJson(0, '添加失败');
            }
        }

        $menuId = $this->request->get('id');

        $menuList = AdminPermService::getTopMenu();

        $this->assign('roleList', $menuList);

        $parent = AdminPerm::where('id', $menuId)-> field('id,name,menu_pid,menu_order,url,icon')->find();

        $this->assign('parent', $parent);

        return $this->returnHtml();
    }

    /**
     * 菜单删除
     */
    public function menuDel()
    {
        if($this->request->isPost()){
            $postData = $this->request->post();

            if(empty($postData['id'])){
                return $this->returnJson(0, '缺少参数');
            }

            $menuId = max(0, intval($postData['id']));

            $menu = AdminRolePermRelation::where('perm_id', $menuId)->find();

            if($menu){
                return $this->returnJson(0, '菜单正在被某个角色使用中，不能直接删除！');
            }

            if(AdminPermService::adminPermDel($menuId)){
                return $this->returnJson(1, '菜单删除成功！');
            }else{
                return $this->returnJson(0, '菜单删除失败！');
            }
        }
    }



}